package com.qujia.station.Interceptor;

import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class SyncDataApiInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求参数
        RequestReaderHttpServletRequestWrapper wrapper = new RequestReaderHttpServletRequestWrapper(request);
        Map<String, String[]> map = request.getParameterMap();
        HashMap<String, String> parameterMap = new HashMap<>();
        for(String key: map.keySet()){
            parameterMap.put(key,map.get(key)[0]);
        }
//        Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        checkSign(parameterMap);
        return true;
    }

    private boolean checkSign(Map pathVariables){
        String timestamp = pathVariables.get("timestamp").toString();

        String sign = pathVariables.get("sign").toString();
        if(StringUtils.isEmpty(sign)){
            throw new CustomException("sign不能为空");
        }

        if (checkIsTimeout(timestamp)) {
            throw new CustomException("请求已超时");
        }

        if (!sign.equals(createSign(timestamp))) {
            throw new CustomException("签名错误");
        }

        return true;
    }

    private boolean checkIsTimeout(String timestamp) {
        if(StringUtils.isEmpty(timestamp)){
            throw new CustomException("时间戳不能为空");
        }
        long tmp = Long.parseLong(timestamp);
//        Long current = System.currentTimeMillis();
//        return current / timestamp == 1 ? current - timestamp > TEN_MINUTE_SECOND * ONE_SECOND_ON_MILLISECODE : current / ONE_SECOND_ON_MILLISECODE - timestamp > TEN_MINUTE_SECOND;
        Long current = System.currentTimeMillis();
        return current / tmp == 1 ? current - tmp > 300L * 1000 : current / 1000 - tmp > 300L;
    }

    private String createSign(String tmp) {
        String encode = "XAh9q" + tmp + "4SSLi";
        return DigestUtils.md5Hex(encode).toUpperCase();
    }
}
